package com.qingke.project_management.command_impl;

import java.util.regex.Pattern;

import org.apache.ibatis.session.SqlSession;

import com.qingke.project_management.App;
import com.qingke.project_management.Console;
import com.qingke.project_management.IDao.OrganizationMapper;
import com.qingke.project_management.IDao.UserMapper;
import com.qingke.project_management.command.Command;
import com.qingke.project_management.pojo.Organization;
import com.qingke.project_management.pojo.User;

public class SignupCommand extends Command {

	public void execute() {
		
		Console.println("欢迎注册");
		User user = new User();
		SqlSession session = getSession();
		UserMapper userMapper = session.getMapper(UserMapper.class);
		
		user = inputUsername(userMapper, user);
		user = inputPassword(user);
		user = inputInfo(user);
		
		userMapper.insert(user);
		session.commit();
		
		user = userMapper.login(user);
		
		App.getInstance().setUser(user);
		Console.println("注册成功,已自动登录");
		
	}

	private User inputInfo(User user){
		String name = "这是一个名字";
		String email = "123@qq.com";
		String phone = "17816";
		int organizationId = 1;
		OrganizationMapper orgMapper = session.getMapper(OrganizationMapper.class);
		Organization organization = orgMapper.selectByPrimaryKey(organizationId);
		user = new User(name, email, phone, organization, organizationId, 
				user.getPassword(), user.getUsername());
		
		return user;
	}
	
	private User inputUsername(UserMapper userMapper,User user){
		String username = Console.askInput("请输入用户名");
		while(true){
			user.setUsername(username);
			if(userMapper.login(user)==null){
				break;
			}
			Console.println(">>Error:用户名已存在");
			username = Console.askInput("请重新输入用户名");
		}
		return user;
	}
	
	private User inputPassword(User user){
		String password = Console.askInput("请输入密码");
		while(true){
			try {
				valid(password);
			} catch (Exception e) {
				Console.println(e.getMessage());
				password = Console.askInput("请重新输入密码");
				continue;
			}
			user.setPassword(password);
			break;
		}
		
		return user;
	}
	
	private void valid(String password) throws Exception {
		Pattern lenPattern = Pattern.compile("[0-9a-zA-z]{6,}");
		if(!lenPattern.matcher(password).find()){
			throw new Exception(">>Error:密码长度必须大于6位");
		}
		
		Pattern numPattern = Pattern.compile("[a-zA-Z]");
		if(!numPattern.matcher(password).find()){
			throw new Exception(">>Error:密码不能为纯数字");
		}
		
		Pattern wordPattern = Pattern.compile("[0-9]");
		if(!wordPattern.matcher(password).find()){
			throw new Exception(">>Error:密码不能为纯字母");
		}
	}
	
}
